#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>
#include <iostream>
#include <unistd.h>

#include "../cunchu_quanju.h"
//服務器類
class Server
{
private:
    /* data */
    int server_id = 0;   //服務器socket文件描述符
    int cont_id = 0;     //客戶機連接後的socket文件描述符
    struct sockaddr_in server_add;
    char buf[4096];     //接受緩衝區

public:
    //服務器啟動
    void Server_start(){
        server_id = socket(AF_INET,SOCK_STREAM,0);
        server_add.sin_family = AF_INET;
        server_add.sin_port = htons(PORT);
        server_add.sin_addr.s_addr = htons(INADDR_ANY);
        if(bind(server_id, (struct sockaddr* )&server_add, sizeof(server_add)) == -1) throw "bind失敗";
        if(listen(server_id, QUEUE) == -1) throw "listen失敗";
        while (/* condition */1)
        {
            /* code */
            socklen_t cont_id_len;
            struct sockaddr_in cont_add;
            cont_id_len = sizeof(cont_add);
            memset(buf,0,sizeof(buf));
            if((cont_id = accept(server_id, (struct sockaddr* )&cont_add, &cont_id_len)) == -1) throw "accept失敗";
            int strlen = recv(cont_id, buf, sizeof(buf),0);
            string str(buf,strlen);
            if(xieyichuli(&str) == -1) throw "存儲層協議處理失敗";
            if(send_ok(cont_id) == -1) throw "給客戶機發送OK信息失敗";
            if(cont_id != 0) close(cont_id);

        }



    }

    //根據接收的信息作處理，出錯返回-1
    int xieyichuli(string *str){
        return 0;
    }

    //處理完客戶機請求後給客戶機返回OK信息，出錯返回-1
    int send_ok(int socket){
        return 0;
    }

    //析構函數關閉socket描述符
    virtual ~Server(){
       if(server_id != 0) close(server_id);
       if(cont_id != 0) close(server_id);
    }
};
